package com.onlyMe.world.objects
{
	import com.flesler.componentas.core.Component;
	import com.onlyMe.base.BasicEntity;
	import com.onlyMe.geom.Coord;
	import com.onlyMe.world.components.grababble.GrababbleComponent;
	
	import flash.utils.IDataInput;
	import flash.utils.IDataOutput;
	import flash.utils.IExternalizable;
	
	public class IsleObject extends BasicEntity implements IExternalizable
	{
		private var _coord:Coord;
		private var _type:String;
		private var _id:int;
		private var _context:IsleObjectContext;
		
		public function IsleObject(type:String, id:int)
		{
			super(type);
			
			_type = type;
			_id = id;
		}
		
		// Utils
		
		private function event(type:String, other:IsleObject=null):void
		{
			dispatchEvent(new IsleObjectEvent(type, other));
		}
		
		// Basic
		
		public function get id():int
		{
			return _id;
		}
		
		public function get type():String
		{
			return _type;
		}
		
		// Context
		
		public function get context():IsleObjectContext
		{
			return _context;
		}
		
		public function set context(v:IsleObjectContext):void
		{
			if (v === context) return;
			
			if (context)
				context.remove(this);
			
			_context = v;
			if (v)
				v.add(this);
			event(IsleObjectEvent.CONTEXT_CHANGED);
		}
		
		// Position
		
		public function get coord():Coord
		{
			return _coord;
		}
		
		public function set coord(v:Coord):void
		{
			_coord = v;
			event(IsleObjectEvent.COORD_CHANGED);
		}
		
		// Activation
		
		public function activate(activator:IsleObject):void
		{
			event(IsleObjectEvent.ACTIVATED_IN_ISLE, activator);
		}
		
		// Component related properties exposed for simplicity
		
		public function get blocks():Boolean
		{
			return getByType(GrababbleComponent) === null;
		}
		
		// Serialization
		
		public function readExternal(input:IDataInput):void
		{
			_coord = Coord.create(input.readByte(), input.readByte());
			
			for each (var component:Component in components)
				if (component is IExternalizable)
					IExternalizable(component).readExternal(input);
		}
		
		public function writeExternal(output:IDataOutput):void
		{
			output.writeByte(coord.x);
			output.writeByte(coord.y);
			
			for each (var component:Component in components)
				if (component is IExternalizable)
					IExternalizable(component).writeExternal(output);
		}
		
		// Disposal
		
		override public function destroy():void
		{
			event(IsleObjectEvent.DESTROYED);
			
			super.destroy();

			_coord = null;
		}
	}
}
